package com.base.cn.platform.os.service.agent.user;

import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.msg.SendMessageUtil;
import com.base.cn.platform.os.common.msg.WXTmpEnum;
import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.dao.agent.user.AgentUserDao;
import com.base.cn.platform.os.entity.agent.income.AgentIncome;
import com.base.cn.platform.os.entity.agent.income.AgentIncomeInfo;
import com.base.cn.platform.os.entity.agent.user.AgentUser;
import com.base.cn.platform.os.service.agent.config.AgentConfigBiz;
import com.base.cn.platform.os.service.agent.income.AgentIncomeBiz;
import com.base.cn.platform.os.service.agent.income.AgentIncomeInfoBiz;
import com.base.cn.platform.os.service.manage.op.affiche.OpReceiveAfficheService;
import com.base.cn.platform.os.service.manage.sysUser.SysUserService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 推广员Biz
 *
 * @author LIZHIPENG
 * @since 2018/5/7
 */
@Service
public class AgentUserBiz extends BaseBiz<AgentUser,AgentUserDao> {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private AgentIncomeBiz agentIncomeBiz;
    @Autowired
    private AgentIncomeInfoBiz agentIncomeInfoBiz;
    @Autowired
    private AgentConfigBiz agentConfigBiz;
    @Autowired
    private OpReceiveAfficheService opReceiveAfficheService;
    @Autowired
    private CustomCacheChannel customCacheChannel;

    /**
     * 统计推广员数量
     * @param agentUser 条件
     * @return BigDecimal
     */
    public BigDecimal count(AgentUser agentUser){
        String whereSql = getWhereSql(agentUser);
        return this.count(whereSql);
    }

    /**
     * 通过用户ID串
     * @param userIds 用户ID串
     * @return Map<BigDecimal,AgentUser>,KEY=用户ID
     */
    public Map<BigDecimal,AgentUser> findAgentUserByUserIds(String userIds){
        List<AgentUser> agentUserList = this.find(" userId in ("+userIds+")",null,null);
        if(ObjectUtils.isNotEmpty(agentUserList)){
            return agentUserList.stream().collect(Collectors.toMap(e->e.getUserId(),e->e));
        }
        return null;
    }

    /**
     * 通过ID串，获取推广员数据
     * @param ids 推广员ID串
     * @return Map<BigDecimal,AgentUser>
     */
    public Map<BigDecimal,AgentUser> findAgentUserByIds(String ids){
        List<AgentUser> agentUserList = this.find(" id in ("+ids+")",null,null);
        if(ObjectUtils.isNotEmpty(agentUserList)){
            return agentUserList.stream().collect(Collectors.toMap(e->e.getId(),e->e));
        }
        return null;
    }

    /**
     * 根据用户ID查询推广员
     * @param userId 用户id
     * @param incomeData 是否设置总收益信息
     * @param invite 是否设置邀请好友权限
     * @param hasSettlement 是否设置有可提现收益
     * @return AgentUser
     */
    public AgentUser findAgentUserByUserId(BigDecimal userId, boolean incomeData, boolean invite, boolean hasSettlement){
        AgentUser agentUser = new AgentUser();
        agentUser.setUserId(userId);
        List<AgentUser> agentUserList = this.queryAgentUserList(agentUser, false, incomeData, false, false);
        this.setInvite(agentUserList, invite);
        if(ObjectUtils.isNotEmpty(agentUserList)){
            return this.hasSettlement(agentUserList.get(0), hasSettlement);
        }
        return null;
    }

    /**
     * 查询推广员列表（分页）
     * @param page 分页
     * @param agentUser 条件
     * @param parentData 是否设置父级推广员：true：是，false：否
     * @param incomeData 是否设置收益信息：true：是，false：否
     * @param userData 是否设置前台关联用户：true：是，false：否
     * @param createUserData 是否设置后台创建用户：true：是，false：否
     * @return
     */
    public PageInfo<AgentUser> queryAgentUserListPage(Pagination page, AgentUser agentUser,boolean parentData, boolean incomeData, boolean userData, boolean createUserData){
        String whereSql = getWhereSql(agentUser);
        PageInfo<AgentUser> agentUserPageInfo = this.findPage(whereSql, page, null);
        agentUserPageInfo.setList(this.setExtendData(agentUserPageInfo.getList(), parentData, incomeData, userData, createUserData));
        return agentUserPageInfo;
    }

    /**
     * 条件查询推广员列表（不分页）
     * @param agentUser 条件
     * @param incomeData
     * @param userData 是否设置前台关联用户：true：是，false：否
     * @param createUserData 是否设置后台创建用户：true：是，false：否
     * @return
     */
    public List<AgentUser> queryAgentUserList(AgentUser agentUser,boolean parentData, boolean incomeData, boolean userData, boolean createUserData){
        String whereSql = getWhereSql(agentUser);
        List<AgentUser> agentUserList = this.find(whereSql, agentUser.getCount(), null);
        return this.setExtendData(agentUserList,parentData,  incomeData, userData, createUserData);
    }

    /**
     * 根据ID查询推广员
     * @param agentUserId 推广员ID
     * @param incomeData 是否设置收益信息：true：是，false：否
     * @param userData 是否设置前台关联用户：true：是，false：否
     * @param createUserData 是否设置后台创建用户：true：是，false：否
     * @return
     */
    public AgentUser findAgentUserById(BigDecimal agentUserId, boolean parentData, boolean incomeData, boolean userData, boolean createUserData){
        if(DataUtil.idIsNotNull(agentUserId)){
            AgentUser agentUser = this.findById(agentUserId, null);
            List<AgentUser> agentUserList = new ArrayList<>();
            agentUserList.add(agentUser);
            this.setExtendData(agentUserList,parentData,  incomeData, userData, createUserData);
            return agentUserList.get(0);
        }
        return null;
    }

    /**
     * 保存推广员
     * @param agentUser
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public Map<String,Object> saveAgentUser(AgentUser agentUser){

        if(!DataUtil.idIsNotNull(agentUser.getId())){
            agentUser.setStatus(3);
            //用户自申请
            if(agentUser.getCreateFrom() == 2){
                boolean flag = agentConfigBiz.getAgentConfig("AGENTUSER");
                if(!flag){
                    return ResultUtil.ERROR("不支持用户申请，请联系后台管理员开通");
                }
                boolean userauditing = agentConfigBiz.getAgentConfig("USERAUDITING");
                if(userauditing){
                    agentUser.setStatus(1);
                }
            }else {
                //去查询学员用户，如果有返回，没有新建之后返回
                Map<String, Object> user = cusUserService.queryUserOrSaveUserByMobile(agentUser.getMobile());
                if(ObjectUtils.isEmpty(user)){
                    return ResultUtil.ERROR("查询用户失败，保存失败");
                }
                AgentUser _agentUser = new AgentUser();
                BigDecimal userId = new BigDecimal((Integer) user.get("id"));
                _agentUser.setUserId(userId);
                List<AgentUser> agentUsers = this.queryAgentUserList(_agentUser, false, false, false, false);
                if(ObjectUtils.isNotEmpty(agentUsers)){
                    return ResultUtil.ERROR("该手机号码已创建分销商");
                }
                agentUser.setUserId(userId);
            }

            this.save(agentUser);

            if(DataUtil.idIsNotNull(agentUser.getParentId())){
                AgentUser parentAgentUser = this.findById(agentUser.getParentId());
                parentAgentUser.setSunNum(parentAgentUser.getSunNum() + 1);
                this.updateById(parentAgentUser, null);
            }

            AgentIncome agentIncome = new AgentIncome();
            agentIncome.setAgentUserId(agentUser.getId());
            agentIncomeBiz.saveOrUpdateAgentIncome(agentIncome);
        }else {
            this.updateById(agentUser, null);
        }
        return ResultUtil.SUCCESS("保存成功", agentUser);
    }

    /**
     * 修改状态
     * @param agentUserIds
     * @param status
     * @return
     */
    public Map<String, Object> updateAgentUserStatus(String agentUserIds, int status){
        AgentUser agentUser = new AgentUser();
        agentUser.setStatus(status);
        this.updateByWhereSql(agentUser, "id in ("+ agentUserIds +")");
        return ResultUtil.SUCCESS("修改成功");
    }


    /**
     * 删除推广员
     * @param agentUserId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteAgentUser(BigDecimal agentUserId) {
        if(DataUtil.idIsNotNull(agentUserId)){
            AgentUser agentUser = this.findAgentUserById(agentUserId, true, false, false, false);
            this.deleteById(agentUserId);

            //如果是二级推广员，修改一级推广员的下线人数
            AgentUser parent = agentUser.getParentAgentUser();
            if(ObjectUtils.isNotEmpty(parent)){
                parent.setSunNum(parent.getSunNum()-1);
                this.updateById(parent, null);
            }

            agentIncomeBiz.deleteAgentIncome(agentUserId);
        }
    }

    /**
     * 审核推广员
     * @param agentUser
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public void aduitAgentUser(AgentUser agentUser){
        this.saveAgentUser(agentUser);
        agentUser = this.findById(agentUser.getId());
        //发送消息
        boolean status = false;
        Map<String,Object> dataMap = new HashMap<>();
        Map<BigDecimal,List> dataListMap = new HashMap<>();
        dataListMap.put(agentUser.getUserId(), Arrays.asList(agentUser));
        dataMap.put("userIdList",Arrays.asList(agentUser.getUserId()));
        dataMap.put("dataListMap",dataListMap);
        if(agentUser.getStatus()==3){//通过
            dataMap.put("key", WXTmpEnum.AGENT_SUCCESS);
            status = true;
        }else if(agentUser.getStatus()==5){//未通过
            dataMap.put("key", WXTmpEnum.AGENT_FAIL);
            status = true;
        }
        if(status){//发送消息
            SendMessageUtil.sendMessage(opReceiveAfficheService,customCacheChannel,dataMap);
        }
    }

    /**
     * 批量导入推广员
     * @param file 文件对象
     * @return Map<String, Object>
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public Map<String, Object> uploadAgentUser(MultipartFile file){
        HSSFWorkbook workBook = null;
        try {
            workBook = new HSSFWorkbook(file.getInputStream());
        } catch (Exception e) {
            return ResultUtil.ERROR("读取xls表格数据错误");
        }
        //只读取sheet1
        HSSFSheet sheet = workBook.getSheetAt(0);
        int rows = sheet.getPhysicalNumberOfRows(); //excel中实际行数
        if (rows <= 1) {
            return ResultUtil.ERROR("xls表格中没有填写数据");
        }
        if (rows > 2001) {
            return ResultUtil.ERROR("xls表中的数据不能多于2000行");
        }

        AgentUser agentUser;
        HSSFRow row;
        HSSFCell cell;
        List<AgentUser> agentUserList = new ArrayList<>();
        Map<String,Integer> _dataMap = new HashMap<>();
        for (int i = 1; i <= rows; i++) {
            agentUser = new AgentUser();
            // 读取行为第二行开始
            row = sheet.getRow(i);
            if (row != null) {
                row.getPhysicalNumberOfCells();
                // **读取行中的列**
                cell = row.getCell((short) 0);//推广员名
                String agentUserName = null;
                if (cell != null) {
                    agentUserName = cell.getStringCellValue();
                    if(!StringUtils.isNotEmpty(agentUserName)){
                        return ResultUtil.ERROR("第" + i + "行中的推广员名不能为空！");
                    }
                    agentUser.setAgentUserName(agentUserName);
                }
                cell = row.getCell((short) 1);//手机号
                String mobile = null;
                if (cell != null) {
                    mobile = cell.getStringCellValue();
                    if (StringUtils.isEmpty(mobile) || !StringUtils.isMobile(mobile)) {
                        return ResultUtil.ERROR( "第" + i + "行中的手机号错误！");
                    }
                    Integer _m = _dataMap.get(mobile.trim());
                    if(ObjectUtils.isNotEmpty(_m)){
                        return ResultUtil.ERROR( "第" + i + "行中的手机号在"+_m+"行中已存在！");
                    }
                    _dataMap.put(mobile.trim(),i);
                    agentUser.setMobile(mobile.trim());
                }
                //设置推广员类型
                agentUser.setUserType(1);

                //分成类型，1表示固定分成
                agentUser.setDivideType(1);

                cell = row.getCell((short) 2);//一级推广员分成比例（%）
                Double oneScale = 0D;
                if (cell != null) {
                    oneScale = cell.getNumericCellValue();
                    if (oneScale.doubleValue()<0D || oneScale.doubleValue()>100D) {
                        return ResultUtil.ERROR( "第" + i + "行中的一级推广员分成比例错误，不能小于0%且大于100%！");
                    }
                    agentUser.setOneScale(oneScale.intValue());
                }

                cell = row.getCell((short) 3);//二级推广员分成比例（%）
                Double twoScale = 0D;
                if (cell != null) {
                    twoScale = cell.getNumericCellValue();
                    if (twoScale.doubleValue()<0D || twoScale.doubleValue()>100D) {
                        return ResultUtil.ERROR( "第" + i + "行中的二级推广员分成比例错误，不能小于0%且大于100%！");
                    }
                    agentUser.setTwoScale(twoScale.intValue());
                }

                cell = row.getCell((short) 4);//二级推广员分成比例（%）
                Double bonusScale = 0D;
                if (cell != null) {
                    bonusScale = cell.getNumericCellValue();
                    if (bonusScale.doubleValue()<0D || bonusScale.doubleValue()>100D) {
                        return ResultUtil.ERROR( "第" + i + "行中的奖金分成比例错误，不能小于0%且大于100%！");
                    }
                    agentUser.setBonusScale(bonusScale.intValue());
                }

                if((agentUser.getTwoScale().doubleValue()+agentUser.getBonusScale().doubleValue())>100D){
                    return ResultUtil.ERROR( "第" + i + "行中的二级推广员分成比例和奖金分成比例和大于100%！");
                }

                cell = row.getCell((short) 5);//结算类型（1随时结，2月结，3年结）
                String settType = null;
                if (cell != null) {
                    settType = cell.getStringCellValue();
                    if (!StringUtils.isNotEmpty(settType) || (!settType.trim().equals("随时结") && !settType.trim().equals("月结") && !settType.trim().equals("年结"))) {
                        return ResultUtil.ERROR( "第" + i + "行中的结算类型错误！");
                    }
                    int _settType = 0;
                    if(settType.trim().equals("随时结")){
                        _settType = 1;
                    }else if(settType.trim().equals("月结")){
                        _settType = 2;
                    }else if(settType.trim().equals("年结")){
                        _settType = 3;
                    }
                    agentUser.setSettType(_settType);
                }

                agentUser.setStatus(1);//设置状态
                agentUser.setCreateFrom(1);//设置创建来源，1表示代创建
                agentUserList.add(agentUser);
            }
        }
        //批量添加
        if(ObjectUtils.isNotEmpty(agentUserList)){
            //创建用户，同时设置用户推广对象的用户ID
            Map<String,Object> resultMap = this.createUserList(agentUserList);
            if((boolean)resultMap.get("success")){
                for (AgentUser user : agentUserList) {
                    this.saveAgentUser(user);
                }
                return ResultUtil.SUCCESS("批量上传成功");
            }
        }
        return ResultUtil.ERROR("系统繁忙，请稍后重试");
    }

    /**
     * 创建用户
     * @param agentUserList
     * @return
     */
    private Map<String,Object> createUserList(List<AgentUser> agentUserList){
        if(ObjectUtils.isNotEmpty(agentUserList)){
            List<String> mobileList =new ArrayList<>();
            for(AgentUser agentUser : agentUserList){
                mobileList.add(agentUser.getMobile().trim());
            }
            List<Map<String,Object>> userMapList = null;
            Map<String,Map<String,Object>> userMobileMaps = null;

            Map<String,Object> resultMap = cusUserService.validateUserMobile(mobileList);
            //如果验证通过，则直接添加
            if((boolean)resultMap.get("success")){
                resultMap = cusUserService.createUserByMobileList(mobileList);
            }else{//如果有部分手机存已注册，则做另一种处理
                //手机号已存在的用户
                userMapList = (List<Map<String,Object>>)resultMap.get("entity");
                String userIds = userMapList.stream().map(e->e.get("id").toString()).collect(Collectors.joining(","));
                Map<BigDecimal,Map<String,Object>> userMaps = userMapList.stream().collect(Collectors.toMap(e->new BigDecimal((Integer) e.get("id")),es->es));
                userMobileMaps = userMapList.stream().collect(Collectors.toMap(e->(String)e.get("mobile"),es->es));
                //查询注册过的手机号是否申请过推广员
                List<AgentUser> _agentUserList = this.find("userId in ("+ userIds +")", null, null);
                if(ObjectUtils.isNotEmpty(_agentUserList)){
                    for(AgentUser _a : _agentUserList){
                        Map<String,Object> treeMap = userMaps.get(_a.getUserId());
                        if(ObjectUtils.isNotEmpty(treeMap)){
                            return ResultUtil.ERROR("手机号:"+(String)treeMap.get("mobile")+"已申请成推广员");
                        }
                    }
                }
                mobileList =new ArrayList<>();
                //如果已注册过的手机号没有申请过推广员
                for(AgentUser agentUser : agentUserList){
                    Map<String,Object> userMap = userMobileMaps.get(agentUser.getMobile().trim());
                    if(ObjectUtils.isEmpty(userMap)){
                        mobileList.add(agentUser.getMobile().trim());
                    }
                }
                //添加
                resultMap = cusUserService.createUserByMobileList(mobileList);
            }
            if((boolean)resultMap.get("success")){
                resultMap = cusUserService.validateUserMobile(mobileList);
                userMapList = (List<Map<String,Object>>)resultMap.get("entity");
                userMobileMaps = userMapList.stream().collect(Collectors.toMap(e->(String)e.get("mobile"),es->es));
                for(AgentUser agentUser : agentUserList){
                    Map<String,Object> userMap = userMobileMaps.get(agentUser.getMobile().trim());
                    agentUser.setUserId(new BigDecimal((Integer)userMap.get("id")));
                }
                return ResultUtil.SUCCESS("推广员用户创建生成");
            }else {
                return ResultUtil.ERROR("系统繁忙，请稍后重试");
            }
        }
        return ResultUtil.ERROR("系统繁忙，请稍后重试");
    }


    /**
     * 修改状态结算收益周期
     * @param settType
     * @return
     */
    public Map<String, Object> alterAgentSettType( int settType,String ids){
        AgentUser agentUser = new AgentUser();
        agentUser.setSettType(settType);
        StringBuilder sql = new StringBuilder("status = 3");
        if(StringUtils.isNotEmpty(ids)){
            sql.append(" and id in (").append(ids).append(" )");
        }
        this.updateByWhereSql(agentUser, sql.toString());
        return ResultUtil.SUCCESS("修改成功");
    }
    //==================================================
    //获取查询语句
    private String getWhereSql(AgentUser agentUser){
        StringBuilder whereSql = new StringBuilder(" 1=1");
        if(ObjectUtils.isNotEmpty(agentUser)){
            if(DataUtil.idIsNotNull(agentUser.getId())){
                whereSql.append(" and id =").append(agentUser.getId());
            }
            if(StringUtils.isNotEmpty(agentUser.getIds())){
                whereSql.append(" and id in (").append(agentUser.getIds()).append(")");
            }
            if(StringUtils.isNotEmpty(agentUser.getAgentUserName())){
                whereSql.append(" and ( agentUserName like concat('%','").append(agentUser.getAgentUserName()).append("','%')")
                        .append("  or  mobile like concat('%','").append(agentUser.getAgentUserName().trim()).append("','%')) ");
            }
            if(DataUtil.idIsNotNull(agentUser.getUserId())){
                whereSql.append(" and userId= ").append(agentUser.getUserId());
            }
            if(StringUtils.isNotEmpty(agentUser.getBeginTime())){
                whereSql.append(" and createTime >= '").append(agentUser.getBeginTime()).append("'");
            }
            if(StringUtils.isNotEmpty(agentUser.getEndTime())){
                whereSql.append(" and createTime <= '").append(agentUser.getEndTime()).append("'");
            }
            if(ObjectUtils.isNotEmpty(agentUser.getUserType())){
                whereSql.append(" and userType=").append(agentUser.getUserType());
            }
            if(DataUtil.idIsNotNull(agentUser.getParentId())){
                whereSql.append(" and parentId=").append(agentUser.getParentId());
            }
            if(ObjectUtils.isNotEmpty(agentUser.getCreateFrom())){
                whereSql.append(" and createFrom=").append(agentUser.getCreateFrom());
            }
            if(ObjectUtils.isNotEmpty(agentUser.getStatus())){
                whereSql.append(" and status=").append(agentUser.getStatus());
            }
        }
        whereSql.append(" order by id desc");
        return whereSql.toString();
    }

    //设置扩展数据
    private List<AgentUser> setExtendData(List<AgentUser> agentUserList,boolean parentData, boolean incomeData, boolean userData, boolean createUserData){
        if(parentData){
            agentUserList = setParentData(agentUserList, parentData);
        }
        if(incomeData){
            agentUserList = setIncomeData(agentUserList, incomeData);
        }
        if(userData){
            agentUserList = setUserData(agentUserList, userData);
        }
        if(createUserData){
            agentUserList = setCreateUserData(agentUserList, createUserData);
        }
        return agentUserList;
    }

    //设置父级推广员数据
    private List<AgentUser> setParentData(List<AgentUser> agentUserList, boolean parentData){
        if(ObjectUtils.isNotEmpty(agentUserList) && parentData){
            String agentUserIds = agentUserList.stream().map(e -> e.getParentId().toString()).distinct().collect(Collectors.joining(","));
            if(!"0".equals(agentUserIds)){
                AgentUser agentUser = new AgentUser();
                agentUser.setIds(agentUserIds);
                List<AgentUser> agentUsers = this.queryAgentUserList(agentUser, false, false, false, false);
                if(ObjectUtils.isNotEmpty(agentUsers)){
                    for (AgentUser user : agentUserList) {
                        if(DataUtil.idIsNotNull(user.getParentId())){
                            for (AgentUser agentUser1 : agentUsers) {
                                if(user.getParentId().equals(agentUser1.getId())){
                                    user.setParentAgentUser(agentUser1);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        return agentUserList;
    }

    //设置收益信息
    private List<AgentUser> setIncomeData(List<AgentUser> agentUserList, boolean incomeData){
        if(ObjectUtils.isNotEmpty(agentUserList) && incomeData){
            String agentUserIds = agentUserList.stream().map(e -> e.getId().toString()).distinct().collect(Collectors.joining(","));
            AgentIncome agentIncome = new AgentIncome();
            agentIncome.setAgentUserIds(agentUserIds);
            List<AgentIncome> agentIncomeList = agentIncomeBiz.queryAgentIncomeList(agentIncome, false);
            if(ObjectUtils.isNotEmpty(agentIncomeList)){
                for (AgentUser agentUser : agentUserList) {
                    for (AgentIncome income : agentIncomeList) {
                        if(agentUser.getId().equals(income.getAgentUserId())){
                            agentUser.setAgentIncome(income);
                            break;
                        }
                    }
                }
            }
        }
        return agentUserList;
    }

    //设置前台关联用户
    private List<AgentUser> setUserData(List<AgentUser> agentUserList, boolean userData){
        if(ObjectUtils.isNotEmpty(agentUserList) && userData){
            String userIds = agentUserList.stream().map(e -> e.getUserId().toString()).distinct().collect(Collectors.joining(","));
            Map<BigDecimal, Map<String, Object>> userMap = cusUserService.queryCusUserMapByUserIds(userIds, false, false, false, false, false, false, false);
            if(ObjectUtils.isNotEmpty(userMap)){
                for (AgentUser agentUser : agentUserList) {
                    agentUser.setUserMap((Map<String, Object>)userMap.get(agentUser.getUserId()));
                }
            }
        }
        return agentUserList;
    }

    //设置后台创建人用户
    private List<AgentUser> setCreateUserData(List<AgentUser> agentUserList, boolean createUserData){
        if(ObjectUtils.isNotEmpty(agentUserList) && createUserData){
            String createUserIds = agentUserList.stream().map(e -> e.getCreateUserId().toString()).distinct().collect(Collectors.joining(","));
            if(StringUtils.isNotEmpty(createUserIds)){
                Map<BigDecimal, Map<String, Object>> sysUserMap = sysUserService.findSysUserMapByUserIds(createUserIds, false, false, false);
                if(ObjectUtils.isNotEmpty(sysUserMap)){
                    for (AgentUser agentUser : agentUserList) {
                        agentUser.setCreateUser(sysUserMap.get(agentUser.getCreateUserId()));
                    }
                }
            }
        }
        return agentUserList;
    }

    /**
     * 设置推广员是否可以邀请好友成为推广员
     * @param agentUserList 推广员列表
     * @param invite 是否设置
     */
    private void setInvite(List<AgentUser> agentUserList, boolean invite){
        if(ObjectUtils.isNotEmpty(agentUserList) && invite){
            for (AgentUser agentUser : agentUserList) {
                if(agentUser.getUserType()==2 || agentUser.getStatus() !=3){
                    agentUser.setInvite(false);
                }else {
                    agentUser.setInvite(agentConfigBiz.getAgentConfig("USERINVITE"));
                }
            }
        }
    }

    /**
     * 设置推广员是否有可结算收益
     * @param agentUser 推广员
     * @param hasSettlement 是否设置可结算收益
     * @return AgentUser
     */
    private AgentUser hasSettlement(AgentUser agentUser, boolean hasSettlement){
        if(ObjectUtils.isNotEmpty(agentUser) && hasSettlement){
            if(agentUser.getStatus() == 3){
                Map<String, Object> map = agentIncomeInfoBiz.queryIsAvailableIncome(agentUser);
                if(ObjectUtils.isNotEmpty(map)){
                    List<AgentIncomeInfo> incomeInfos =(List<AgentIncomeInfo>) map.get("incomeInfos");
                    if(ObjectUtils.isNotEmpty(incomeInfos)){
                        //可结算
                        agentUser.setHasSettlement(true);
                        return agentUser;
                    }
                }
            }
            agentUser.setHasSettlement(false);

            String[] currentDateArr = (DateUtils.format(new Date(), "yyyy-MM-dd")).split("-");

            String currentYear = currentDateArr[0];
            int _currentYear = Integer.parseInt(currentYear);

            int days= 0;
            if(agentUser.getSettType() == 2){
                //当前月
                String currentMonth = currentDateArr[1];
                int _currentMonth = Integer.parseInt(currentMonth);
                if(_currentMonth<12){
                    days = DateUtils.daysBeforeNow(DateUtils.parseDate(_currentYear + "-" + (_currentMonth + 1) + "-01", "yyyy-MM-dd"));
                }else {
                    days = DateUtils.daysBeforeNow(DateUtils.parseDate((_currentYear+1) + "-01-01", "yyyy-MM-dd"));
                }
            }else if (agentUser.getSettType() == 3){
                days = DateUtils.daysBeforeNow(DateUtils.parseDate((_currentYear+1) + "-01-01", "yyyy-MM-dd"));
            }

            agentUser.setDays(days);
        }
        return agentUser;
    }

}
